import axios from "axios";
import { createDiscreteApi } from 'naive-ui'
import { usrSetState } from '@/apis/index'
const { message } = createDiscreteApi(['message'])
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
axios.defaults.withCredentials = true; // 配合 sever cookie 跨域
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_URL,
  timeout: 30000
})
service.interceptors.request.use(
  (config) => {
    // loadingBar.start();
    const isToken = (config.headers || {}).isToken === false
    const token = localStorage.getItem('t') || '';
    if (!isToken && token) {
      token && (config.headers.Authorization = `Bearer ${token}`);
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

service.interceptors.response.use((response) => {
  if (response.data.status === 200 || response.status === 201) {
    return response.data;
  } else if (response.data.status === 403) {
    // Notify(response.data.msg);
    return response.data;
  }
  else if (response.data.status === 401 || response.data.status === 404) {
    // Notify(response.data.msg);
    return Promise.reject(response);
  } else if (response.data === 401) {
    // Notify('身份过期！请重新登录, 5秒后退出');
    // setTimeout(() => {
    //   Store.commit('user/REMOVE_USER_INFO');
    //   router.push('/login');
    // }, 5000);
  } else if (response.data === 404) {
    // Notify('身份过期！请重新登录, 5秒后退出');
  } else if (response.data.status === 200) {
    return response;
  }
  return response;
}, error => {
  console.info(error)
  const { status } = error.response;
  if (status === 401) {
    setTimeout(async () => {
      message.error('身份过期！请重新登录');
      await usrSetState({ username: localStorage.getItem('u') as string, state: '0' })
      localStorage.removeItem('t');
      localStorage.removeItem('u');
      localStorage.removeItem('designation');
      localStorage.removeItem('l');
      localStorage.removeItem('day');
      localStorage.removeItem('countLevel');
      localStorage.removeItem('avatar');
      location.reload()
    }, 0)
  }
  return Promise.reject(error);
})


export default service;